Laravel / Controller / Pass data from controller to view
Pass the data from controller to view
-
STEP
1 Rule
view() is used to pass the data to view blade. Second parameter of the view() must be an array. $ sign and array key is used to access the data in view 2. Pass the data to view
return view('student_index', ['name'=> 'Anisha','email'=>'Nishka','mobile'=>'Sumit']); OR $data= ['name'=> 'Anisha','email'=>'Nishka','mobile'=>'Sumit']; return view('student_index', $data); OR $data['name']="Anisha"; $data['email']="m@gmail.com"; $data['mobile']="77887988"; return view('student_index', $data); namespace App\Http\Controllers; class StudentController extends Controller { public function index() { $data['name']="Anisha"; $data['email']="m@gmail.com"; $data['mobile']="77887988"; return view('student_index', $data); } } 3. Show the data in view blade
array key and prepend $ sign is used to show the variables in the view page Eg:
to access name , use $nameto acces email, use $email;
to acces mobile, use $mobile;
Name {{$name}} Email {{$email}} Mobile {{$mobile}} 4. Pass multi-dimensional array
in controller
namespace App\Http\Controllers; class StudentController extends Controller { public function index() { $data['student'][]= ['name'=> 'Anisha','email'=>'a@gmail.com','mobile'=>'212121']; $data['student'][]= ['name'=> 'Anu','email'=>'b@gmail.com','mobile'=>'Su345345mit']; $data['student'][]= ['name'=> 'sree','email'=>'s@gmail.com','mobile'=>'56565']; return view('student_index', $data ); } } in view
We can access the data with key, here the key is 'student'. So we can use $student in the view blade
{{$row['name']}} {{$row['email']}} {{$row['mobile']}}